#include "LogFile.h"

#include <sstream>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

using std::string;
using std::ostringstream;

string LogFile::dirName = "log";
string LogFile::separator = "\r\n";

LogFile::LogFile(const std::string& filename):m_fd(-1)
{
	createLogFile(filename);
}

LogFile::LogFile():m_fd(-1)
{
	time_t timep;
	time(&timep);
	tm* p;
	p = localtime(&timep);
	ostringstream ostr;
	ostr << getpid() << '_' << p->tm_mon + 1 << '-'
	     << p->tm_mday << '_' 
		 << p->tm_hour << ':' 
		 << p->tm_min << ':'
		 << p->tm_sec;
	createLogFile(ostr.str());
}

LogFile::~LogFile()
{
	if (m_fd >= 0)
	{
		close(m_fd);
	}
}

int LogFile::createLogFile(const string& filename)
{
	if (0 != access(dirName.c_str(), F_OK))
	{
		mkdir(dirName.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
	}

	string path(dirName);

	path = path + '/' + filename + ".log";

	m_fd = creat(path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

	if (m_fd < 0)
	{
		return -1;
	}
}

void LogFile::write(const std::string& log)
{
	string str(log + separator);
	::write(m_fd, str.c_str(), str.size());
}

